<?php
namespace app\common\service\WebSocket\SocketService; 

use app\model\BbcModel\BusinessGoods;
use app\Normal;
use app\BaseService;
use app\common\service\GoodsService\GoodsService;
use app\model\BbcModel\GoodsClass;
use app\model\BbcModel\GoodsTags;
use app\model\BbcModel\Goods;
use app\model\BbcModel\GoodsSpecPrice;

class GoodsSocketService extends BaseService
{
    public $socket_connector;

    public $fd;

    public $host;
    public $pageLimit      = 2000;
    
    public function goodslistExport($parameters = []) {
        ini_set('memory_limit', '3096M');
        $this->socket_connector = $parameters['socket'];
        $this->fd               = $parameters['fd'];
        $this->host             = $parameters['host'];
        $data                   = $parameters['requestData'];
        $data['cid']            = $parameters['_master_user']['cid'];
        if($parameters['_master_user']['cb_id']>0){
            $data['cb_id']= $parameters['_master_user']['cb_id'];
        }
        $check= callApi(GoodsService::class, 'makeWhere',$data);
        $where=$check['where'];
        $sql=$check['sql'];
        if($parameters['_master_user']['cb_id']>0){
            $dbModel= BusinessGoods::instance()->alias('bs')
                    ->leftjoin('goods g','bs.goods_id=g.id');
        }else{
            $dbModel= Goods::instance()->alias('g');
        }
        $query=$dbModel->field('g.*,gc.name as goods_class_name,gb.name as goods_brand_name')
                ->leftjoin('goods_class gc','gc.id=g.class_id')
                ->leftjoin('goods_brand gb','gb.id=g.brand_id')
                ->where($where);
        if($sql){
           $query=$query->where($sql); 
        }
        $total_count=$query->count();
        $total_page  = ceil($total_count / $this->pageLimit);
        $importData  = [];
        for ($page = 0; $page < $total_page; $page++) {
            $list=$query->order('g.id desc')
                ->limit($page * $this->pageLimit, $this->pageLimit)
                ->select()
                ->toArray();        
            if ($list) {
                $tmpData = [];                
                foreach ($list as $v) {
                    $classname='';
                    $firstclassname='';
                    if($v['class_id']){
                        $goodsclass= GoodsClass::instance()->info(['id'=>$v['class_id']]);
                        $classname=$goodsclass['name']??'';
                    }
                    if(isset($goodsclass['pid'])){
                        $fgoodsclass= GoodsClass::instance()->info(['id'=>$goodsclass['pid']]);
                        $firstclassname=$fgoodsclass['name']??'';
                    }
                    $supply_tagname='';
                    $tagname='';
                    if($v['supply_tag']){
                        $supplytags= GoodsTags::instance()->where([['type','=',0],['id','in',$v['supply_tag']]])->column('name');
                        $supply_tagname=$supplytags?implode(',', array_column($supplytags, 'name')):'';
                    }
                    if($v['tag']){
                        $tags= GoodsTags::instance()->where([['type','=',0],['id','in',$v['tag']]])->column('name');
                        $tagname=$tags?implode(',', array_column($tags, 'name')):'';
                    }
                    $tmpData[] = [
                        $v['id'],
                        $v['name'],
                        $firstclassname,
                        $classname,
                        $v['class_id'],
                        $v['goods_brand_name'],
                        $v['brand_id'],
                        Goods::instance()->is_bonded[$v['is_bonded']],
                        $v['status']==0?'下架':'上架',
                        $v['skucode'],
                        $v['barcode'],
                        $v['tax_rate'],
                        $v['price_cost'],
                        $v['price'],
                        $v['price_market'],
                        $v['price_vip'],
                        $v['num_storage'],
                        $v['origin'],
                        $v['weight']?bcdiv($v['weight'], 1000,2):0,
                        $v['isfree_postfee']==0?'否':'是',
                        $supply_tagname,
                        $tagname
                    ];
                }
                $importData = array_merge($importData, $tmpData);
            }

            if ($page == $total_page - 1) {
                $percent = 98.00; //预留给写文件使用
            } else {
                $percent = bcdiv($page, $total_page - 1, 4);
                $percent = bcmul($percent, 100, 2);
            }

            if ($this->socket_connector) {
                $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
                    'percent' => $percent,
                ]);
                $send = json_encode($send, JSON_UNESCAPED_UNICODE);
                $this->socket_connector->push($this->fd, $send);
            }
        }
        //数据准备完成开始写入excel本地数据
        $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
            'percent' => 99.00,
        ]);
        $send = json_encode($send, JSON_UNESCAPED_UNICODE);
        $this->socket_connector->push($this->fd, $send);

        $fileName     = "商品导出";
        $headArr      = $this->getColumns();
        $data         = $importData;
        $download_url = xlsxFileLocalStorage($headArr, $data, $fileName, $this->host);
        return Normal::returnWsStatus(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $download_url,
            'name'=>'商品导出'
        ]);
    }
     //excel头部
    public function getColumns() {
        return [
            'id',
            '商品名称',
            '一级分类',
            '二级分类',
            '分类id',
            '品牌',
            '品牌id',
            '商品类型',
            '状态',
            'SKU',
            '国际条码',
            '税率',
            '成本价',
            '建议零售价',
            '市场价',
            '推荐会员价',
            '库存',
            '产地',
            '重量',
            '供应商是否包邮',
            '供应商标签',
            '自定义标签'
        ];
    }
}
